/**
 * 
 */

package com.wutianyi.thrift.example.threads;

import org.apache.thrift.TException;
import org.apache.thrift.server.TServer;

import com.wutianyi.thrift.ThreadsTest;

/**
 * @author wutianyi
 * 
 */
public class ThreadsHandler implements ThreadsTest.Iface {

	TServer	server;

	public ThreadsHandler(TServer server) {

		this.server = server;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wutianyi.thrift.ThreadsTest.Iface#stop()
	 */
	@Override
	public int stop() throws TException {

		System.out.println("stop");
		server.stop();
		return 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wutianyi.thrift.ThreadsTest.Iface#threadFour(int)
	 */
	@Override
	public int threadFour(int sleep) throws TException {

		System.out.println("threadFour");
		go2Sleep(4, sleep);
		return 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wutianyi.thrift.ThreadsTest.Iface#threadOne(int)
	 */
	@Override
	public int threadOne(int sleep) throws TException {

		System.out.println("threadOne");
		go2Sleep(1, sleep);
		return 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wutianyi.thrift.ThreadsTest.Iface#threadThree(int)
	 */
	@Override
	public int threadThree(int sleep) throws TException {

		System.out.println("ThreadThree");
		go2Sleep(3, sleep);
		return 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wutianyi.thrift.ThreadsTest.Iface#threadTwo(int)
	 */
	@Override
	public int threadTwo(int sleep) throws TException {

		System.out.println("ThreadTwo");
		go2Sleep(2, sleep);
		return 1;
	}

	void go2Sleep(int thread, int seconds) {

		for(int i = 0; i < seconds; i++) {
			System.out.printf("Thread %d: sleep %d\n", thread, i);
			try {
				Thread.sleep(1000);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.printf("Thread %d Done\n", thread);
	}

	public TServer getServer() {

		return server;
	}

	public void setServer(TServer server) {

		this.server = server;
	}

}
